from django.http import JsonResponse
from system.models import Manager
from system.models import Department
from django.core import serializers
from common.page_util import page_util, page_low_util
import json
import uuid


def manager_page(request):
    data = json.loads(request.body)
    page = data['page']
    limit = data['limit']
    params = data['params']
    manager_list = Manager.objects.all()
    response = page_low_util(manager_list, page, limit)
    return JsonResponse(response)


# 根据id获取管理员信息
def manager_info(request, id):
    manager_info = Manager.objects.get(id=id)
    manager_info.password = ''
    result = json.loads(manager_info.toJSON())
    return JsonResponse(result, safe=False)


# 根据id获取部门信息
def department_info(request, id):
    department_info = Department.objects.get(id=id)
    result = json.loads(department_info.toJSON())
    return JsonResponse(result, safe=False)


# 新增用户
def manager_add(request):
    response = {}
    data = json.loads(request.body)
    manager = Manager.objects.create(
        id=uuid.uuid1(),
        name=data['name'],
        mail=data['mail'],
        department_id=data['departmentId'],
        password=data['password'],
        role=data['role'])
    if not manager is None:
        response['status'] = 200
        response['msg'] = '用户新建成功'
        return JsonResponse(response)
    else:
        response['status'] = 400
        response['msg'] = '用户新建失败'
        return JsonResponse(response)


# 更新用户
def manager_update(request):
    response = {}
    data = json.loads(request.body)
    try:
        manager = Manager.objects.get(id=data['id'])
        manager.name = data['name']
        manager.mail = data['mail']
        manager.department_id = data['departmentId']
        manager.role = data['role']
        if data['password'] != '':
            manager.password = data['password']
        manager.save()
    except Exception:
        response['status'] = 400
        response['msg'] = '更新失败'
        return JsonResponse(response)
    response['status'] = 200
    response['msg'] = '更新成功'
    return JsonResponse(response)


# 删除用户
def manager_delete(request, id):
    response = {}
    try:
        manager = Manager.objects.filter(id=id)
        manager.delete()
    except Exception:
        response['status'] = 400
        response['msg'] = '删除失败'
        return JsonResponse(response)
    response['status'] = 200
    response['msg'] = '删除成功'
    return JsonResponse(response)
